package com.cvpoc.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.web.struts.DispatchActionSupport;

import com.cvpoc.dto.FormationInitialeDTO;
import com.cvpoc.exception.BusinessException;
import com.cvpoc.service.FormationInitialeService;
import com.cvpoc.struts.form.FormationInitialeForm;

public class FormationInitialeAction extends DispatchActionSupport {
	private static final DateTimeFormatter FMT = DateTimeFormat
			.forPattern("MM/yyyy");

	public ActionForward consulterListe(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			FormationInitialeService service = (FormationInitialeService) getWebApplicationContext()
					.getBean("formationInitialeService");
			List<FormationInitialeDTO> formationsInitialesDTO = service
					.findListFormationInitialeByIdCollaborateur((Integer) request
							.getSession().getAttribute("idCollaborateur"));
			request.setAttribute("formations", formationsInitialesDTO);
			return mapping.findForward("success");
		} catch (BusinessException e) {
			return mapping.findForward("failure");
		}
	}

	public ActionForward afficherFormAjout(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		FormationInitialeForm formationInitialeForm = (FormationInitialeForm) form;
		formationInitialeForm.init();
		return mapping.findForward("success");
	}

	public ActionForward supprimer(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FormationInitialeService service = (FormationInitialeService) getWebApplicationContext()
				.getBean("formationInitialeService");
		service.deleteFormationInitiale(Integer.valueOf(request
				.getParameter("idFormationInitiale")));
		return consulterListe(mapping, form, request, response);
	}

	public ActionForward afficherFormModification(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// request.setAttribute("action", "modifier");

		FormationInitialeService service = (FormationInitialeService) getWebApplicationContext()
				.getBean("formationInitialeService");

		FormationInitialeForm formulaire = (FormationInitialeForm) form;

		FormationInitialeDTO formationInitialeDTO = service
				.findFormationInitialeById(Integer.valueOf(request
						.getParameter("idFormationInitiale")));
		formulaire.setDateDebut((formationInitialeDTO.getDateDebut()
				.toString(FMT)));
		formulaire
				.setDateFin((formationInitialeDTO.getDateFin().toString(FMT)));
		formulaire.setLibelle(formationInitialeDTO.getLibelle());
		formulaire.setId(String.valueOf(formationInitialeDTO.getId()));
		return mapping.findForward("success");
	}

	public ActionForward ajouter(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		FormationInitialeService service = (FormationInitialeService) getWebApplicationContext()
				.getBean("formationInitialeService");
		FormationInitialeForm formulaire = (FormationInitialeForm) form;
		service.createFormationInitiale(getFormationInitialeDTO(formulaire,
				(Integer) request.getSession().getAttribute("idCollaborateur")));
		return mapping.findForward("ajoutSuccess");
	}

	public ActionForward modifier(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		FormationInitialeService service = (FormationInitialeService) getWebApplicationContext()
				.getBean("formationInitialeService");
		FormationInitialeForm formulaire = (FormationInitialeForm) form;
		service.updateFormationInitiale(getFormationInitialeDTO(formulaire,
				(Integer) request.getSession().getAttribute("idCollaborateur")));
		return mapping.findForward("modifSuccess");
	}

	/**
	 * renvoie l'objet DTO correspondant au formulaire passé en paramètre
	 * 
	 * @param formulaire
	 * @return
	 * @throws ParseException
	 */
	private FormationInitialeDTO getFormationInitialeDTO(
			FormationInitialeForm formulaire, int idCollaborateur)
			throws ParseException {
		FormationInitialeDTO formationInitialeDTO = new FormationInitialeDTO();
		formationInitialeDTO.setId_collaborateur(idCollaborateur);
		formationInitialeDTO.setDateDebut(FMT.parseDateTime(formulaire
				.getDateDebut()));
		formationInitialeDTO.setDateFin(FMT.parseDateTime(formulaire
				.getDateFin()));
		formationInitialeDTO.setLibelle(formulaire.getLibelle());
		if (formulaire.getId() != null) {
			formationInitialeDTO.setId(Integer.valueOf(formulaire.getId()));
		}
		return formationInitialeDTO;
	}

	public ActionForward genererPDF(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FormationInitialeService service = (FormationInitialeService) getWebApplicationContext()
				.getBean("formationInitialeService");

		// return an application file instead of html page
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition",
				"attachment;filename=formationInitiale.pdf");
		String generatedFullName = service
				.genererPDFListeFormationInitialeByIdCollaborateur((Integer) request
						.getSession().getAttribute("idCollaborateur"));
		if (StringUtils.isNotBlank(generatedFullName)) {
			// Get it from file system
			FileInputStream in = new FileInputStream(
					new File(generatedFullName));
			// Get it from web path
			// jndi:/localhost/StrutsExample/upload/superfish.zip
			// URL url = getServlet().getServletContext()
			// .getResource("upload/superfish.zip");
			// InputStream in = url.openStream();

			// Get it from bytes array
			// byte[] bytes = new byte[4096];
			// InputStream in = new ByteArrayInputStream(bytes);
			ServletOutputStream out = response.getOutputStream();

			byte[] outputByte = new byte[4096];
			// copy binary content to output stream
			while (in.read(outputByte, 0, 4096) != -1) {
				out.write(outputByte, 0, 4096);
			}
			in.close();
			out.flush();
			out.close();
		}
		return null;
	}
}
